package com.vito.oa.act.extend.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.vito.base.authoriza.dao.CreateIdMapper;
import com.vito.base.model.DataGrid;
import com.vito.base.model.ResMsg;
import com.vito.base.model.Result;
import com.vito.base.util.JSONUtil;
import com.vito.base.util.Pty;
import com.vito.base.util.StringUtil;
import com.vito.base.util.Validata;
import com.vito.oa.act.constant.OaActContants;
import com.vito.oa.act.extend.dao.OaActApprovalFormMapper;
import com.vito.oa.act.extend.dao.OaActExBussDefMapper;
import com.vito.oa.act.extend.model.OaActExTableColsModel;
import com.vito.oa.act.extend.service.OaActApprovalFormService;

import static com.vito.oa.act.constant.OaActContants.CACHE_ACT_VALUE;

@Service
public class OaActApprovalFormServiceImpl implements OaActApprovalFormService {
	private static final Logger log = LoggerFactory.getLogger(OaActApprovalFormService.class);
	private static String dialect="oracle";
	static{
		Pty pty  = null;
		try {
			pty = Pty.get("conf/jdbc");
		} catch (Exception e) {
		}
		if(pty!=null){
			dialect = pty.getProp("sql.dialect");
		}
	}
	
	@Autowired
	private OaActApprovalFormMapper actApprovalFormMapper;
	@Autowired
	private OaActExBussDefMapper actExBussDefMapper;
	@Autowired
	private CreateIdMapper createIdMapper;
	
	@Override
	@CacheEvict(value=CACHE_ACT_VALUE,allEntries=true)
	public Result saveForm(String user_id,String rootDeptId,String details) {
		Result r = new Result();
		try {
			if(Validata.isNullOrEmpty(details) 
			|| Validata.isNullOrEmpty(user_id) 
			|| Validata.isNullOrEmpty(rootDeptId)){
				r.setCode(Result.CODE_PARA_ERROR);
				r.setMsg(ResMsg.E31);
				return r;
			}
			JSONObject json = JSONUtil.convertString2JsonObject(details);
			//取得表单元素信息
			JSONArray cols = json.getJSONArray("cols");
			if(cols==null||cols.size()==0){
				r.setCode(Result.CODE_PARA_ERROR);
				r.setMsg(ResMsg.E31);
				return r;
			}
			String detail_key = StringUtil.getUUID();
			saveFormDetails(detail_key, cols);
			//取得表单基本信息
			Map<String, String> formMap = new HashMap<String, String>();
			//保存表单基本信息
			String ref_key = StringUtil.getUUID();
			formMap.put("form_id", ref_key);
			formMap.put("form_name", json.getString("form_name"));
			formMap.put("form_des", json.getString("form_des"));
			formMap.put("user_id", user_id);
			formMap.put("dept_id", rootDeptId);
			formMap.put("encrypt", json.getString("encrypt"));
			actApprovalFormMapper.saveForm(formMap);
			//保存流程节点扩展信息
			Map<String, String> bussDefRef = new HashMap<String, String>();
			bussDefRef.put("refKey", ref_key);
			bussDefRef.put("tableKey", OaActContants.COMM_TABLE_KEY);
			bussDefRef.put("detailKey", detail_key);
			bussDefRef.put("operType", OaActContants.COMM_OPER_TYPE);
			bussDefRef.put("isMore", OaActContants.COMM_IS_MORE);
			actExBussDefMapper.saveActExBussDefRef(bussDefRef);
			r.setCode(Result.CODE_OK);
			r.setMsg(ResMsg.SAVESUC);
		} catch (Exception e) {
			log.error("保存用户自定义表单异常：", e);
			r.setCode(Result.CODE_ERROR);
			r.setMsg(ResMsg.EXECERR);
		}
		return r;
	}
	public void saveFormDetails(String detail_key,JSONArray cols) throws Exception{
		//遍历表单元素
		for (int i = 0; i < cols.size(); i++) {
			JSONObject col = cols.getJSONObject(i);
			OaActExTableColsModel colModel = new OaActExTableColsModel();
			colModel.setTableKey(OaActContants.COMM_TABLE_KEY);
			String col_name = col.getString("col_name");
			if(Validata.isNullOrEmpty(col_name)){
				colModel.setColName("col"+i);
			}else{
				colModel.setColName(col_name);
			}
			colModel.setColNameCh(col.getString("col_name_ch"));
			colModel.setIsFk(OaActContants.BASE_STATE_DIS);
			colModel.setIsPk(OaActContants.BASE_STATE_DIS);
			colModel.setShowType(col.getString("show_type"));
			colModel.setOperators("=");
			//下拉框，添加下拉数据到act_ex_user_code表
			if(OaActContants.FORM_SHOWTYPE_SELECT.equals(col.getString("show_type"))
					||OaActContants.FORM_SHOWTYPE_MSELECT.equals(col.getString("show_type"))){
				String data = col.getString("data_id");
				if(data!=null&&data.length()>0){
					String sels [] = data.split(",");
					if(sels!=null&&sels.length>0){
						String batchId = "UC"+createIdMapper.getId("ACT_EX_UC");
						for (int j = 0; j < sels.length; j++) {
							Map<String, String> userCode = new HashMap<String,String>();
							userCode.put("batchid", batchId);
							userCode.put("code_name", sels[j]);
							userCode.put("order_num", j+"");
							actApprovalFormMapper.saveUserCode(userCode);
						}
						colModel.setDataId(batchId);
					}
				}
			}
			colModel.setIsRequire(col.getString("is_require"));
			Object obj = col.get("properties");
			if(obj != null){
			 	
				if(obj instanceof JSONObject){
					colModel.setProperties(((JSONObject)obj).toJSONString());	
				}else if(obj instanceof String){
					colModel.setProperties(obj.toString());
				}
			}
			if("mysql".equals(dialect)) {
				colModel.setColType(OaActContants.FORM_COL_TYPE_MYSQL_VARCHAR);
				
			}else {
				colModel.setColType(OaActContants.FORM_COL_TYPE_VARCHAR);
			}
			
			if(OaActContants.FORM_SHOWTYPE_TEXTAREA.equals(col.getString("show_type"))){
				colModel.setColLength(OaActContants.COL_SMALL_LENGTH);
			}else{
				colModel.setColLength(OaActContants.COL_LARGE_LENGTH);
			}
			colModel.setIsProcess(OaActContants.BASE_STATE_DIS);
			colModel.setIsQueryCol(OaActContants.BASE_STATE_DIS);
			colModel.setIsShowCol(OaActContants.BASE_STATE_DIS);
			colModel.setOrderNum(i+1);
			String colKey = createIdMapper.getId("col_key");
			colModel.setColKey(colKey);
			//保存表单元素
			actApprovalFormMapper.saveActExTableCols(colModel);
			actApprovalFormMapper.saveActEExTableCols(colModel);
			Map<String, String> bussDefRefCol = new HashMap<String, String>();
			bussDefRefCol.put("detailKey", detail_key);
			bussDefRefCol.put("colKey", colModel.getColKey());
			//保存表单元素对应关系
			actExBussDefMapper.saveActExBussDefRefCol(bussDefRefCol);
		}
		Map<String, String> bussDefRefCol = new HashMap<String, String>();
		bussDefRefCol.put("detailKey", detail_key);
		bussDefRefCol.put("colKey", OaActContants.COMM_COL_ID);
	}
	@Override
	@CacheEvict(value=CACHE_ACT_VALUE,allEntries=true)
	public Result updateForm(String user_id, String details) {
		Result r = new Result();
		try {
			if(Validata.isNullOrEmpty(details) 
			|| Validata.isNullOrEmpty(user_id) ){
				r.setCode(Result.CODE_PARA_ERROR);
				r.setMsg(ResMsg.E31);
				return r;
			}
			
			JSONObject json = JSONUtil.convertString2JsonObject(details);
			//取得表单元素信息
			JSONArray cols = json.getJSONArray("cols");
			if(cols==null||cols.size()==0){
				r.setCode(Result.CODE_PARA_ERROR);
				r.setMsg(ResMsg.E31);
				return r;
			}
			String detail_key = StringUtil.getUUID();
			saveFormDetails(detail_key, cols);
			Map<String, String> formMap = new HashMap<String, String>();
			//保存表单基本信息
			formMap.put("form_id", json.getString("form_id"));
			formMap.put("form_name", json.getString("form_name"));
			formMap.put("form_des", json.getString("form_des"));
			actApprovalFormMapper.updateForm(formMap);
			
			String refKey = json.getString("form_id");
			actApprovalFormMapper.deleteFormCols(refKey);
			actApprovalFormMapper.deleteEExFormCols(refKey);
			actExBussDefMapper.deleteActExBussDefRefCol(refKey);
			
			Map<String, String> bussDefRef = new HashMap<String, String>();
			bussDefRef.put("detailKey", detail_key);
			bussDefRef.put("refKey", json.getString("form_id"));
			actApprovalFormMapper.updateBussDefRef(bussDefRef);
			r.setCode(Result.CODE_OK);
			r.setMsg(ResMsg.UPDSUC);
		} catch (Exception e) {
			log.error("保存用户自定义表单异常：", e);
			r.setCode(Result.CODE_ERROR);
			r.setMsg(ResMsg.EXECERR);
		}
		return r;
	}
	@Override
	public DataGrid<Map<String, String>> queryForm(Map<String, String> map) {
		DataGrid<Map<String, String>> data = new DataGrid<Map<String, String>>();
			data.setRows(actApprovalFormMapper.queryFormByPage(map));
			data.setTotal(Integer.valueOf(String.valueOf(map.get("total"))));
		return data;
	}
	@Override
	public List<Map<String, String>> queryFormCols(String form_id) {
		return actApprovalFormMapper.queryFormCols(form_id);
	}
	@Override
	@CacheEvict(value=CACHE_ACT_VALUE,allEntries=true)
	public Result deleteForm(String form_id) {
		Result r = new Result();
		try {
			int count = actApprovalFormMapper.queryFormProcessCount(form_id);
			if(count>0){
				r.setCode(Result.CODE_PARA_ERROR);
				r.setMsg("该表单已被流程关联，请删除对应的流程再进行表单删除操作");
				return r;
			}
			actApprovalFormMapper.deleteFormCols(form_id);
			actApprovalFormMapper.deleteEExFormCols(form_id);
			actExBussDefMapper.deleteActExBussDefRefCol(form_id);
			actApprovalFormMapper.deleteForm(form_id);
			actExBussDefMapper.deleteActExBussDefRef(form_id);
			r.setCode(Result.CODE_OK);
			r.setMsg(ResMsg.DELSUC);
		} catch (Exception e) {
			log.error("删除自定义表单异常：", e);
			r.setCode(Result.CODE_ERROR);
			r.setMsg(ResMsg.EXECERR);
		}
		return r;
	}
	
}
